//利用子进程去运行爬虫脚本
//开启一个child的子进程去启动爬虫脚本 并且监听爬虫脚本运行的情况
const cp = require('child_process')
const { resolve } = require('path')
import mongoose from 'mongoose'
const Movie = mongoose.model('Movie')
;(async ()=>{
    const script = resolve(__dirname,'../crawler/trailer-list');
    const child = cp.fork(script,[]);
    //判断进程是否调用过
    let invoked = false;

    child.on('error',err => {
        if(invoked){

            return

        }else{
            invoked = true;
        }
        console.log(error)
    })

    child.on('exit',code => {
        if(invoked){

            return

        } else {
            
            invoked = false;
            let err = code === 0 ? null : new Error('exit code' + code)

            console.log(err)
        }
    })

    child.on('message',data => {
        let result = data.result
        console.log(result)
        result.forEach(async item => {
            // 判断此数据是否已经存过数据库了
            let movie = await Movie.findOne({
                doubanId: item.doubanId
            })  
            if (!movie) {
                movie = new Movie(item)
                await movie.save()
            }

        })
    })




})()